//多人点餐消息同步socket
import useDinerStore from "@/store/diner"
import useUserStore from "@/store/user"

let socketTask: any = null
let socketConnected = false

export const connectSocket = () => {
	const dinerStore = useDinerStore()
	const userStore = useUserStore()
	if (!dinerStore.tableId || !userStore.user.id) {
		closeSocket()
		return
	}
	console.log("connectSocket", {
		tableId: dinerStore.tableId,
		lvUserId: userStore.user.id,
	})
	closeSocket()
	uni.connectSocket({
		url: import.meta.env.VITE_APP_SOCKET_URL,
	})
	uni.onSocketOpen(() => {
		console.log("onSocketOpen")
		socketConnected = true
		uni.sendSocketMessage({
			data: JSON.stringify({
				action: "table_dining_user_join",
				requestBody: {
					tableId: dinerStore.tableId,
					lvUserId: userStore.user.id,
				},
			}),
		})
		socketTask = setInterval(() => {
			uni.sendSocketMessage({
				data: JSON.stringify({
					action: "ping",
				}),
			})
		}, 4000)
	})
	uni.onSocketMessage((res: any) => {
		console.log("onSocketMessage", res)
		let data = JSON.parse(res.data)
		let message = JSON.parse(data.requestBody)
		//缓存消息通知
		dinerStore.updateSocketMessage({
			action: data.action,
			message,
			messageId: Math.random(),
		})
		let currentPages = getCurrentPages()
		//全局监听清台弹窗
		if (data.action == "table_state_clear") {
			//强制跳转到扫码首页
			if (currentPages.length && currentPages?.[currentPages?.length - 1]?.route != "pages/index/open") {
				uni.showModal({
					title: "提示",
					content: "桌台已清，请重新扫码点餐码",
					showCancel: false,
					success: (res) => {
						if (res.confirm) {
							//清空数据,关闭连接
							dinerStore.updateDinerId("")
							dinerStore.updateTableId("")
							closeSocket()
							uni.reLaunch({ url: "/pages/index/open" })
						}
					},
				})
			}
		}
	})
	uni.onSocketError((res: any) => {
		console.log("onSocketError", res)
		setTimeout(() => {
			connectSocket()
		}, 2000)
	})
	uni.onSocketClose((res: any) => {
		socketConnected = false
		console.log("onSocketClose", res)
	})
}

export const closeSocket = () => {
	socketTask && clearInterval(socketTask)
	socketConnected && uni.closeSocket()
}
